package com.ea.modular.controller.sys;


import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ea.common.annotation.LogAnnotation;
import com.ea.common.node.ZTreeNode;

import com.ea.common.page.PageInfoBT;
import com.ea.common.parent.controller.BaseController;
import com.ea.common.utils.ToolUtil;

import com.ea.modular.model.sys.Role;
import com.ea.modular.model.sys.ShiroUser;
import com.ea.modular.service.sys.RoleService;
import com.ea.modular.utils.sys.UserUtil;


import io.swagger.annotations.ApiOperation;

/**
 * 角色控制器
 * @author jun
 *
 */
@Controller
@RequestMapping("/role")
public class RoleController extends BaseController {

	private String PREFIX = "/system/role/";
	
	@Autowired
	private RoleService roleService;
	
	
	/**
	 * 跳转到角色管理首页
	 */
	@RequestMapping("")
	@RequiresPermissions("sys:role:view")
	public String index() {
		return PREFIX + "role";
	}

	

	/**
	 * 角色列表
	 * @param role
	 * @return
	 */
	@LogAnnotation
	@ApiOperation(value = "角色列表")
	@RequestMapping(value = "/list",method=RequestMethod.POST)
	@ResponseBody
	public Object list(Role role){
		
		PageInfoBT<Role> findPage = roleService.findPage(role);
		return findPage;
	}
	
	
	/**
	 * 角色删除
	 * @return
	 */
	@LogAnnotation
	@ApiOperation(value = "角色")
	@RequestMapping(value = "/delete",method=RequestMethod.POST)
	@ResponseBody
	public int delete(String id) {
		//清除角色与用户的缓存信息
		UserUtil.clearRoleCache();
		roleService.deleteAuthority(id);
		return roleService.delete(id);
	}
	
	
	
	/**
	 * 角色详情页
	 * @return
	 */
	@ApiOperation(value = "角色详情")
	@RequestMapping(value = "/form",method=RequestMethod.GET)
	public String form(Model model,Role role,String type) {

		//判断是否为修改页
		if(type.equals("update")) {
			Role r = UserUtil.getRoleById(role.getId());
		
			model.addAttribute("role",r);
			//跳转修改页
			return PREFIX + "role_edit";
		}

		//跳转添加页
		return PREFIX + "role_add";
	}
	
	
	/**
	 * 角色管理
	 * @return
	 */
	@LogAnnotation
	@ApiOperation(value = "角色编辑")
	@RequestMapping(value = "/save",method=RequestMethod.POST)
	@ResponseBody
	public int save(Role role,String type) {
		//清除角色的缓存
        UserUtil.clearRoleCache();
		//判断是否为修改
		if(type.equals("update")) {
			return roleService.update(role);
		}
		
		return roleService.insert(role);
	}
	
	/**
	 * 角色授权页
	 * @return
	 */
	@ApiOperation(value = "角色授权")
	@RequestMapping(value = "/role_assign",method=RequestMethod.GET)
	public String role_assign(String id,Model model) {
		Role r = UserUtil.getRoleById(id);
		model.addAttribute("roleName",r.getName());
		model.addAttribute("roleId",r.getId());
		return PREFIX + "role_assign";
	}
	
	
	/**
	 * 角色授权菜单
	 * @return
	 */
	@LogAnnotation
	@ApiOperation(value = "角色授权菜单")
	@RequestMapping(value = "/setAuthority",method=RequestMethod.POST)
	@ResponseBody
	public int setAuthority(String roleId,String ids) {
	    ShiroUser shiroUser = UserUtil.getCurrentUser();
	    List<String> list = new ArrayList<String>();
	    String[] lt = ids.split(",");
	    for (String str : lt) {
	    	if(!str.equals("")){
	    		list.add(str);
	    	}
	    	
		}
	 
		return roleService.setAuthority(roleId,list,shiroUser.getId());
	}
	
	
	
	
	 /**
     * 获取角色列表
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "/roleTreeListByUserId/{userId}")
    @ResponseBody
    public List<ZTreeNode> roleTreeListByUserId(@PathVariable String userId) {
       
    	List<String> roleIds = roleService.getRoleIds(userId);
        if (ToolUtil.isEmpty(roleIds)) {
            List<ZTreeNode> roleTreeList = this.roleService.roleTreeList();
            return roleTreeList;
        } else {
            List<ZTreeNode> roleTreeListByUserId = this.roleService.roleTreeListByUserId(roleIds);
            return roleTreeListByUserId;
        }
    }
    
    
    /**
	 * 用户授权到角色
	 * @return
	 */
	@LogAnnotation
	@ApiOperation(value = "用户授权到角色")
	@RequestMapping(value = "/setUserRoleAuthority",method=RequestMethod.POST)
	@ResponseBody
	public int setUserRoleAuthority(String userId,String ids) {
	    ShiroUser shiroUser = UserUtil.getCurrentUser();
	    List<String> list = new ArrayList<String>();
	    String[] lt = ids.split(",");
	    for (String str : lt) {
	    	if(!str.equals("")){
	    		list.add(str);
	    	}
	    	
		}
	 
		return roleService.setUserRoleAuthority(userId,list,shiroUser.getId());
	}
	
	
	
	/*
	 * 返回String类型的结果
	 * 检查用户名的合法性,如果用户已经存在，返回false，否则返回true(返回json数据，格式为{"valid",true})
	 */
	@RequestMapping(value = "/checkRoleName",method=RequestMethod.POST)
	@ResponseBody
	public String checklogin(String name,String id) {

		boolean result = true;
		Role r = UserUtil.getRoleByName(name);
		if(r!=null) {
			if(!r.getId().equals(id)){
				result=false;
			}
		}
		
		return ToolUtil.getValidator(result);
	}
	
}
